﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Caching;
using HomeFramework.Model;
using System.Diagnostics;
using HomeFramework.Core;
using System.ServiceModel.Activation;
using System.ServiceModel.Routing;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace HomeFramework.Services
{
    [ServiceContract()]
    public interface IHomeFrameworkService
    {
        [OperationContract(ReplyAction = "*", Action = "*")]
        ProcessMessageResponse ProcessMessage(ProcessMessageRequest request);
    }

    [MessageContract]
    public class ProcessMessageRequest
    {
        [MessageBodyMember]
        public byte[] messageBody { get; set; }
        [MessageBodyMember]
        public string messageVersion { get; set; }
        [MessageBodyMember]
        public string serviceName { get; set; }
        [MessageBodyMember]
        public string serviceVersion { get; set; }
        [MessageBodyMember]
        public string bindingType { get; set; }
    }

    [DataContract(Namespace = "http://tempuri.org/")]
    [MessageContract]
    public class ProcessMessageResponse
    {
        [MessageBodyMember]
        [DataMember]
        public byte[] messageBody { get; set; }
    }

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
    public class HomeFrameworkService : IHomeFrameworkService
    {
        public ProcessMessageResponse ProcessMessage(ProcessMessageRequest request)
        {
            using (var ts = new TransactionScript())
            {
                var s = ts.FindByName(request.serviceName, request.serviceVersion);
                if (s == null)
                {
                    Log.WriteLine(Log.SourceEnum.HomeFrameworkEngine, TraceEventType.Verbose, "Unable to find service {0}", request.serviceName);
                    throw new FaultException(new FaultReason("Unable to find service " + request.serviceName));
                }

                var bytes = request.messageBody;
                var risp = HomeFrameworkEngine.MessageGenerator.ProcessMessage(s, bytes, request.messageVersion, request.bindingType);
                return new ProcessMessageResponse { messageBody = risp };
            }
        }
    }
}